package query;

import index.BucketScan;
import index.HashIndex;
import index.HashScan;
import parser.AST_CreateIndex;
import parser.ParseException;
import relop.Schema;
import relop.Tuple;
import global.Minibase;
import global.RID;
import global.SearchKey;
import heap.HeapFile;
import heap.HeapScan;

/**
 * Execution plan for creating indexes.
 */
class CreateIndex implements Plan {

	protected Schema schema;
	protected String fileName;
	protected String ixColumn;
	protected String ixTable;
	/**
	 * Optimizes the plan, given the parsed query.
	 * 
	 * @throws QueryException
	 *             if index already exists or table/column invalid
	 */

	public CreateIndex(AST_CreateIndex tree) throws QueryException {

		ixTable = tree.getIxTable();
		schema = QueryCheck.tableExists(ixTable);
		ixColumn = tree.getIxColumn();
		QueryCheck.columnExists(schema, ixColumn);
		fileName = tree.getFileName();
		QueryCheck.fileNotExists(fileName);
		
	} // public CreateIndex(AST_CreateIndex tree) throws QueryException

	/**
	 * Executes the plan and prints applicable output.
	 */
	public void execute() {

		HeapFile hp = new HeapFile(ixTable);
		HashIndex hi = new HashIndex(fileName);
		HeapScan scan = hp.openScan(); 
		RID rid = new RID();
		
		while(scan.hasNext()){
			Tuple t = new Tuple(schema, scan.getNext(rid));
			hi.insertEntry(new SearchKey(t.getField(ixColumn)), rid);
		}
		
		scan.close();
		Minibase.SystemCatalog.createIndex(fileName, ixTable, ixColumn);
		// print the output message
		System.out.println("Create index for column" + ixColumn + " in table " + ixTable +" for file " + fileName);

	} // public void execute()

} // class CreateIndex implements Plan
